package net.rock.config;

import lombok.Data;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterConfig {
    private List<String> nodes;
    private Integer maxTotal;
    private Integer maxIdle;
    private Integer minIdle;

    @Bean
    public JedisCluster initJedisCluster() {
        System.out.println("initJedisC");
        System.out.printf("nodes:%s%n", nodes);
        Set<HostAndPort> set = nodes
                .stream()
                .map(node -> {
                    String[] split = node.split(":");
                    return new HostAndPort(split[0], Integer.parseInt(split[1]));
                })
                .collect(Collectors.toSet());
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        return new JedisCluster(set, config);
    }
}
